from flask import request, url_for
from flask_login import current_user
from .models import Auth
from .utils import generate_tree2, get_children

def get_menu():
    # 获取登录角色id
    auth_ids = []
    if current_user.role.auths:
        for auth in current_user.role.auths:
            auth_ids.append(auth.id)
    menu = Auth.menu_tree(auth_ids)
    return menu

''' 判断导航菜单是否选中 '''
def is_selected(**args):
    has_selected = False
    # return True
    # 超级管理员
    if "url" not in args:
        return has_selected
    
    now_path = request.path

    if "children"  in args:
        # print(args.get('children'))
        auths = get_children(args.get('children'))
        for child in auths:
            if url_for(child.url) == now_path:
                has_selected = True
                break
    else:
        has_selected = True if now_path == url_for(args.get('url')) else False

    return has_selected

def my_repeat(length):
    return '|--' + (length * '----')

def register_func(app):
    app.add_template_global(get_menu, "get_menu")
    app.add_template_global(is_selected, "is_selected")

    app.add_template_filter(my_repeat, "my_repeat")

